{% extends 'common/base.html' %}
{% block css %}
    <style>
        .score {
            width: 40px;
        }

        .type1 {
            color: #00c0ef;
            border: 1px solid #00c0ef;
            padding-right: 5px;
        }

        .type2 {
            color: #4fc08d;
            border: 1px solid #4fc08d;
            padding: 0 3px;
        }

        .type3 {
            color: #F76377;
            border: 1px solid #F76377;
            padding: 0 3px;
        }

        .type4 {
            color: #A06AD2;
            border: 1px solid #A06AD2;
            padding: 0 3px;
        }

        .type5 {
            color: #C9A310;
            border: 1px solid #C9A310;
            padding: 0 3px;
        }
    </style>
{% endblock %}
{% block content %}
    <section class="content-header">
        <div>
            <ol class="breadcrumb">
                <li><a href="#"><i class="fa fa-dashboard"></i> 题库管理</a></li>
                <li class="active">添加试卷</li>
            </ol>
        </div>
    </section>
    <section class="content" id="showcontent">
        <div class="row">
            <div class="col-md-12">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">添加试卷</h3>
                    </div>
                    <form method="post" class="form-horizontal" onsubmit="return false">
                        <div class="box-body">
                            <div class="form-group">
                                <label for="input_test_name" class="control-label col-xs-4">
                                    <label for="test_name">试卷名称</label></label>
                                <div class="col-xs-4">
                                    <input class="form-control" id="test_name" name="test_name" placeholder="输入试卷名称"
                                           type="text">
                                </div>

                            </div>
                            <div class="form-group">
                                <label for="input_score" class="control-label col-xs-4">
                                    <label for="score">总分</label></label>
                                <div class="col-xs-4">
                                    <input class="form-control" id="total_score" name="total_score" readonly value="0"
                                           type="text">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="input_state" class="col-xs-4 control-label">
                                    <label for="state">是否启用</label></label>
                                <div class="radio col-md-8">
                                    <ul id="state">
                                        <li>
                                            <input checked id="state-0" name="state" type="radio" value="0">
                                            <label for="state-0">否</label>
                                        </li>
                                        <li>
                                            <input id="state-1" name="state" type="radio" value="1">
                                            <label for="state-1">是</label>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="input_is_public" class="col-xs-4 control-label">
                                    <label for="is_pulic">是否公开</label>
                                </label>
                                <div class="radio col-md-8">
                                    <ul id="is_public">
                                        <li>
                                            <input checked id="is_public-0" name="is_public" type="radio" value="0">
                                            <label for="is_public-0">否</label>
                                        </li>
                                        <li>
                                            <input id="is_public-1" name="is_public" type="radio" value="1">
                                            <label for="is_public-1">是</label>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            {#题目#}
                            <div>
                                <div class="box-body table-responsive no-padding">
                                    <table class="table table-striped toggle-arrow-tiny" data-paging="false">
                                        <thead>
                                        <tr>
                                            <th><input type="checkbox" onclick="selectAll()" id="selAll"></th>
                                            <th>编号</th>
                                            <th>题目</th>
                                            <th>类型</th>
                                        </tr>
                                        </thead>
                                         <tbody id="tabData">
                                        </tbody>
                                    </table>
                                </div>
                                <div class="box-footer clearfix" id="pagination">
                                </div>
                            </div>
                            {#已选题目#}
                            <div class="theme-config">
                                <div class="theme-config-box">
                                    <div class="spin-icon">
                                        <span class="badge badge-warning float-right" id="num">0</span>
                                    </div>
                                    <div class="skin-settings">
                                        <div class="title" id="title">
                                            已选题目
                                            <span id="avg_score" hidden>
                                                每题 <input type='text' name="avg_score" style="width: 30px"/>分
                                            </span>
                                        </div>
                                        <div style="max-height: 500px;overflow: auto">
                                            <ul id="selected">
                                                {% for result in results %}
                                                    <li class="qt" data-id="{{ result[0] }}" id="{{ result[0] }}">
                                                        <span>{{ result[0] }}.</span>
                                                        <span class='type{{ result[3] }}'>{{ result[2] }}</span>
                                                        <span class="context" data-context="{{ result[1] }}"></span>
                                                        <div class='float-right'>
                                                            <input type='text' id="score{{ result[0] }}" name="score"
                                                                   class="score"
                                                                   placeholder="分数" onchange="calculate_total()"/>
                                                            <a href='javascript:delsel({{ result[0] }})'>
                                                                <i class="fa fa-times"></i>
                                                            </a>
                                                        </div>
                                                    </li>
                                                {% endfor %}
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="box-footer" style="text-align: center">
                            <button type="btn" onclick="tijiao()" class="btn btn-primary">提交</button>
                            <a href="{{ url_for("main.test_list") }}" class="float-right btn">返回</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
{% endblock %}
{% block js %}
    <script>
        var questionIds = [];
        $(function () {
            $("#state").addClass("list-inline");
            $("#state li").css("margin", "0 40px");
            $("#is_public").addClass("list-inline");
            $("#is_public li").css("margin", "0 40px");

            $(".context").each(function () {
                var context = $(this).data('context');
                if (context.length > 10) {
                    context = context.substr(0, 10) + "…";
                }
                $(this).html(context)
            })
            loadData(1);


        });

        $('.spin-icon').click(function () {
            $(".theme-config-box").toggleClass("show");
        });

        //初始化
        function init() {
            var num = $("#selected li").length
            $("#num").html(num);
            $('.qt').each(function () {
                questionIds.push(parseInt($(this).data('id')));
            })
            setavg(num);
        }

        init();

        //全选
        function selectAll() {
            $("input[type='checkbox']").each(function () {
                if ($(this).prop("checked") == true) {
                    $("input[type='checkbox']").prop('checked', true);
                    check(this);
                    return;
                } else {
                    $("input[type='checkbox']").prop('checked', false);
                    check(this);
                    return;
                }
            });
        }

        //删除已选题
        function delsel(id) {
            $("li").remove("#" + id);
            $("#num").html($("#selected li").length);
            $("#ck" + id).prop('checked', false);
            delarray(id);
            setavg($("#selected li").length);
        }

        //平均分设置框的显示
        function setavg(num) {
            if (num > 0) {
                $("#avg_score").show()
            }
            if (num == 0) {
                $("#avg_score").hide()
            }
        }

        //加载数据
        function loadData(page) {
            $.post("{{ url_for('main.getResource')}}", {"page": page}, function (res) {
                var str = "";
                var pagain = "";
                for (var v = 0; v < res.items.length; v++) {
                    if (checkId(res.items[v].id)) {
                        str += "<tr><td><input type=\"checkbox\" checked value=\"" + res.items[v].id + "\" name=\"questionIds\" id=\"ck" + res.items[v].id + "\" onclick=\"check(this)\"></td>";
                    } else {
                        str += "<tr><td><input type=\"checkbox\" value=\"" + res.items[v].id + "\" name=\"questionIds\" id=\"ck" + res.items[v].id + "\" onclick=\"check(this)\"></td>";
                    }
                    str += "<td data-toggle=\"collapse\" data-target=\"#op" + res.items[v].id + "\">" + res.items[v].id + "</td>" +
                        "<td style='text-algin:left;' data-toggle=\"collapse\" data-target=\"#op" + res.items[v].id + "\">" + res.items[v].context + "</td>" +
                        "<td data-toggle=\"collapse\" data-target=\"#op" + res.items[v].id + "\"> " + res.items[v].name + "</td>" +
                        "</tr><tr>" +
                        "<td colspan=\"4\" style=\"margin: 0;padding: 0\">" +
                        "<div style=\"text-align: left;margin: 5px 50px\" id=\"op" + res.items[v].id + "\" class=\"collapse\">" +
                        "<div> <strong>" + res.items[v].name + "</strong></div>" +
                        "<div style=\"margin:5px 20px \"><strong>" + res.items[v].context + " </strong></div> <div>" +
                        "<div style=\"float:left;\">" +
                        "<p style=\"float:left; margin: 5px 20px\">A. " + res.items[v].op_a + " </p>" +
                        "<p style=\"float:left; margin: 5px 20px\">B. " + res.items[v].op_b + " </p></div><div style=\"float:left;\">" +
                        "<p style=\"float:left; margin: 5px 20px\">C. " + res.items[v].op_c + " </p>" +
                        "<p style=\"float:left; margin: 5px 20px\">D. " + res.items[v].op_d + " </p></div></div>" +
                        "<div style=\"clear: left;color:#008000\"> 答案：  " + res.items[v].answer + " </div>" +
                        "<div><p><strong>所属用户：</strong>" + res.items[v].username + "</p>" +
                        "</div></div></td></tr>"
                }
                $("#tabData").html(str)
                pagain += "<div style=\"vertical-align:middle;text-align: center\">" +
                    "<ul class=\"pagination pagination-sm\">" +
                    "<li><a href=\"javascript:loadData(1)\">首页</a></li>";
                if (res.has_prev) {
                    pagain += "<li><a href=\"javascript:loadData(" + res.prev_num + ")\">上一页</a></li>";
                } else {
                    pagain += "<li class=\"disabled\"><a href=\"#\">上一页</a></li>";
                }
                for (var v = 1; v <= res.pages; v++) {
                    if (v == res.page) {
                        pagain += "<li class=\"active\"><a href=\"#\">" + v + "</a></li>";
                    } else {
                        pagain += "<li><a href=\"javascript:loadData(" + v + ")\">" + v + "</a></li>";
                    }
                }
                if (res.has_next) {
                    pagain += "<li><a href=\"javascript:loadData(" + res.next_num + ")\">下一页</a></li>";
                } else {
                    pagain += "<li class=\"disabled\"><a href=\"#\">下一页</a></li>";
                }

                pagain += "<li><a href=\"javascript:loadData(" + res.pages + ")\">尾页</a></li></ul>" +
                    "<div class=\"pagination float-right pagination-sm\">共" + res.pages + "页" + res.total + "条记录</div></div>";
                $("#pagination").html(pagain);
                $("#selAll").prop('checked', false);
                checkSelected();
            })
        }

        //提交
        function tijiao() {
            var test_name = $("#test_name").val();
            var score = $("#total_score").val();
            var state = $('input[name="state"]:checked').val();
            var is_public = $('input[name="is_public"]:checked').val();
            if (test_name == null || score == null || questionIds.length == 0) {
                return false
            }
            scores = getScores();
            if (!scores) {
                layer.open({
                    title: '警告',
                    content: "请检查每题的分值",
                    icon: 2,
                    times: 2000
                });
                return false;
            }
            var tip = layer.load(0, {shade: false});
            $.post("{{ url_for("main.test_add") }}", {
                "test_name": test_name,
                "score": score,
                "state": state,
                "is_public": is_public,
                "questionIds": questionIds,
                "scores": scores
            }, function (res) {
                layer.close(tip);
                layer.open({
                    title: '成功',
                    content: "创建试卷成功！",
                    icon: 1,
                    times: 2000,
                    end: function () {
                        location.href = "{{ url_for('main.test_list') }}";
                    }
                });

            })
        }

        //获得最后的分数
        function getScores() {
            var scores = [];
            for (var id in questionIds) {
                var score = $("#score" + questionIds[id]).val();
                if (score == '' || score == 0) {
                    return false;
                }
                scores.push(score)
            }
            return scores;
        }

        //删除
        function delarray(id) {
            var flag = $.inArray(parseInt(id), questionIds);
            if (flag >= 0) {
                questionIds.splice(flag, 1);
                return
            }
        }

        //检查
        function checkId(id) {
            var flag = $.inArray(parseInt(id), questionIds);
            if (flag >= 0) {
                return true;
            }
            return false
        }

        //根据已选题目修改选题
        function checkSelected() {
            $('input[name="questionIds"]').each(function () {
                var id = parseInt($(this).val());
                var index = $.inArray(id, questionIds);
                if (index >= 0) {
                    $(this).prop('checked', true);
                } else {
                    $(this).prop('checked', false);
                }
            })

        }

        //设置平均分数
        $("#avg_score").change(function () {
            var score = $("input[name='avg_score']").val();
            $('input[name="score"]').val(score);
            calculate_total()
        })

        //计算总分
        function calculate_total() {
            var total = 0;
            $("input[name='score']").each(function () {
                total += parseInt($(this).val());
            })
            $("#total_score").val(total)
        }

        //加入已选题目
        function check(row) {
            if (!(row['name'] == "questionIds")) {
                return
            }
            var context = $(row).parent().parent("tr").find("td:eq(2)").text();
            var type = $(row).parent().parent("tr").find("td:eq(3)").text().replace(/\s+/g, "");
            var type_id = 1;
            if (type == "多选题") {
                type_id = 2
            } else if (type == "判断题") {
                type_id = 3
            } else if (type == "填空题") {
                type_id = 4
            } else if (type == "简答题") {
                type_id = 5
            }
            if (context.length > 10) {
                context = context.substr(0, 10) + "…";
            }
            if ($(row).is(":checked") && !(checkId(row['value']))) {
                $("#selected").append("<li id=\"" + row['value'] + "\"><span>" + row['value'] + ".</span><span class='type" + type_id + "'>" + type + "</span><span>" + context + "</span><div  class='float-right'><input type='text' id=\"score" + row['value'] + "\" name=\"score\" class=\"score\" placeholder=\"分数\" onchange=\"calculate_total()\"/> <a href='javascript:delsel(" + row['value'] + ")'><i class=\"fa fa-times\"></i></a></div></li>");
                questionIds.push(parseInt(row['value']));
            } else if (!($(row).is(":checked")) && (checkId(row['value']))) {
                $("li").remove("#" + row['value']);
                delarray(row['value']);
            }
            $("#num").html($("#selected li").length);
            setavg($("#selected li").length);
        }

    </script>
{% endblock %}